package net.zjitc.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class FileController {
    @RequestMapping(value = "/fileUpLoad.do")
    @ResponseBody
    public Map<String,Object> fileUpLoad(@RequestParam("desc") String desc,
                                         @RequestParam("file") MultipartFile file,
                                         HttpServletRequest request){

        Map<String,Object> map = new HashMap<>();
        if (file!=null){
            String path =request.getServletContext().getRealPath("/WEB-INF/upload/");
            String fileName = UUID.randomUUID()+file.getOriginalFilename();
            File filePath = new File(path,fileName);
            if (!filePath.getParentFile().exists()){
                filePath.getParentFile().mkdirs();
            }
            //上传文件保存在一个目标文件中
            try {
                file.transferTo(new File(path+File.separator+fileName));
                map.put("success",true);
            } catch (IOException e) {
                e.printStackTrace();
                map.put("success",false);
            }
        }else {
            map.put("success",false);
        }
        return map;
    }

    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(@RequestParam("filename") String filename,
                                           HttpServletRequest request) throws Exception {
        /*指定下载的路径*/
        String path = request.getServletContext().getRealPath("/WEB-INF/download/");
        /*创建该文件对象*/
        File file = new File(path+File.separator+filename);
        /*设置响应头*/
        HttpHeaders headers = new HttpHeaders();
        /*tomcat7及以下需要设置编码*/
        String downloadFilename = new String(filename.getBytes("UTF-8"),"iso-8859-1");
        /*通知浏览器以attachment(下载方式)打开图片*/
        headers.setContentDispositionFormData("attachment",downloadFilename);
        /*二进制数据流*/
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        /*响应状态HttpStatus.OK，表示服务器已经处理*/
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
    }
}
